#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <cstring>

void ChildWrite(int fd)
{
    char buffer[1024] = {0};
    int cnt = 0;
    while(true)
    {
        snprintf(buffer,sizeof(buffer),"子进程，pid=%d，cnt=%d",getpid(),cnt++);
        write(fd,buffer,strlen(buffer));
        sleep(1);
    }
}
void FatherRead(int fd)
{
    char buffer[1024] = {0};
    while (true)
    {
        buffer[0] = 0;
        ssize_t n =  read(fd,buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n] = 0;
            std::cout<<buffer<<std::endl;
        }

    }
    
}

int main(){
    int fds[2] = {0};
    int ret = pipe(fds);
    if(ret < 0)
    {
        std::cerr << "pipe失败" <<std::endl;
        return 1;
    }
    pid_t id = fork();
    if(id == 0)
    {
        //子进程
        close(fds[0]);
        ChildWrite(fds[1]);
        close(fds[1]);
        exit(0);
    }
    close(fds[1]);
    FatherRead(fds[0]);
    waitpid(id,nullptr,0);
    close(fds[0]);
    return 0;
}